# -*- coding: utf-8 -*-
from datetime import datetime, timedelta

from odoo import models, fields, api,_
from odoo.exceptions import ValidationError, UserError


class HROvertime(models.Model):
    _name = 'hr.overtime.sheet.real'
    _approve_by_level=True
    _order = 'apply_date desc'
    _inherit = ['portal.mixin', 'mail.thread', 'mail.activity.mixin', 'utm.mixin', 'base.approve']
    _description = u'实际加班单'
    sheet_id=fields.Many2one('hr.overtime.sheet',ondelete='restrict')

    department_id = fields.Many2one('hr.department', string=u'部门',related='sheet_id.department_id',store=True)
    apply_date = fields.Date(string=u'日期',related='sheet_id.apply_date',store=True)
    name = fields.Char(related='sheet_id.name',string='单号')
    type_id = fields.Many2one('hr.overtime.type', string=u'加班类别',related='sheet_id.type_id')
    line_ids = fields.One2many('hr.overtime', related='sheet_id.line_ids')
    user_id = fields.Many2one('res.users', default=lambda self: self.env.uid)
    def action_set_to_draft(self):
        self.state='draft'


    state = fields.Selection([
        ('draft', u'草稿'),
        ('cancel', u'取消'),
        ('to approve', u'待审核'),
        ('rejected', u'拒绝'),
        ('done', u'完成')
        ],default='draft')


    name=fields.Char(string=u'单号',related='sheet_id.name' ,store=True)
    user_id = fields.Many2one('res.users', related='sheet_id.user_id' ,store=True)

    department_id=fields.Many2one('hr.department',string=u'部门',related='sheet_id.department_id',store=True)
    apply_date=fields.Date(string='加班日期',related='sheet_id.apply_date',store=True)
    real_period=fields.Float(compute='compute_real_period')

    approve_flow_ids = fields.One2many('approve.flow', 'res_id', domain=[('res_model', '=', 'hr.overtime.sheet.real')])

    approval_record_ids = fields.One2many('approval.records', 'res_id',
                                          domain=[('res_model', '=', 'hr.overtime.sheet.real')])

    _sql_constraints = [
        ('name_uniq', 'unique (name)', "单号我必须唯一!"),
    ]

    # _sql_constraints = [
    #     ('name_uniq', 'unique (department_id,apply_date)', "员工每天只能申请一次加班!"),
    # ]
    #
    # def get_total_amount(self):
    #     return self.real_period
    def compute_real_period(self):
        for record in self:
            if record.real_time_start and record.real_time_end:
                real_period=record.real_time_end-record.real_time_start
                hour,min,s=str(real_period).split(':')
                # print (hour)
                # print (min)
                # print (s)
                hour=int(hour)
                min=int(min)/60
                if min>=0.5:
                    min=0.5
                else:
                    min=0
                record.real_period=hour+min
            else:
                record.real_period=0
            # week_day=str(record.apply_date.weekday()+1)
            #

            #
            # data=self.env['hr.attendance.row'].search([('employee_id','=',self.employee_id.id),('attendance_type','=','o'),('weekday','=',week_day)])
            # if data:
            #     record.real_period=data.check_time-am_up










    # @api.onchange('apply_date','request_hour_from','request_hour_to')
    # def compute_period(self):
    #     for record in self:
    #         if (not record.apply_date) or (not record.request_hour_from) or (not record.request_hour_to):
    #             return
    #         dayofweek = record.apply_date.weekday()+1
    #         lunch_hour=0
    #
    #         print (dayofweek)
    #         if record.employee_id.resource_calendar_id:
    #             attendances=record.employee_id.resource_calendar_id.attendance_ids.filtered(lambda x:x.dayofweek==str(dayofweek))
    #             if attendances:
    #                 hour_to=attendances[-1].hour_to
    #                 if hour_to>float(record.request_hour_from):
    #                     raise UserError('加班起始时间不能大于下班时间')
    #             else:
    #                 lunch_hour=record.employee_id.resource_calendar_id.lunch_time+record.employee_id.resource_calendar_id.dinner_time
    #
    #             record.period=float(record.request_hour_to)-float(record.request_hour_from)-lunch_hour
    #         else:
    #             record.period=record.request_hour_to-record.request_hour_from-lunch_hour
            # if record.period<0:
            #     raise UserError('结束时间不能小于开始时间')


    #
    # @api.constrains('request_hour_from', 'request_hour_to')
    # def check_dates(self):
    #     if self.filtered(lambda leave: leave.request_hour_from > leave.request_hour_to):
    #         raise ValidationError(_('The start date of the time off must be earlier end date.'))

    # @api.constrains('date_from', 'date_to', 'state', 'employee_id')
    # def _check_date(self):
    #     for holiday in self.filtered('employee_id'):
    #         domain = [
    #             ('apply_date', '=', holiday.apply_date),
    #             ('employee_id', '=', holiday.employee_id.id),
    #             ('id', '!=', holiday.id),
    #             ('state', 'not in', ['cancel', 'rejected']),
    #         ]
    #         nholidays = self.search_count(domain)
    #         if nholidays:
    #             raise ValidationError(
    #                 _('同一个员工同一天不能申请两次加班'))
    #
    # @api.model
    # def create(self, vals):
    #     if not vals.get('name') or vals['name'] == _('New'):
    #         vals['name'] = self.env['ir.sequence'].next_by_code('hr.overtime') or _('New')
    #     return super(HROvertime, self).create(vals)



